package it.fuesi.expired.formbinders;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.MultiAutoCompleteTextView;

import java.io.ByteArrayOutputStream;

import it.fuesi.expired.FormActivity;
import it.fuesi.expired.R;
import it.fuesi.expired.adapters.AbstractAdapter;
import it.fuesi.expired.adapters.TagsAdapter;
import it.fuesi.expired.api.client.AttachmentsBroker;
import it.fuesi.expired.api.client.ItemsBroker;
import it.fuesi.expired.fragments.DatePickerFragment;
import it.fuesi.expired.model.Attachment;
import it.fuesi.expired.model.Item;
import it.fuesi.expired.model.base.AModel;

/**
 * Created by pascotto on 22/08/14.
 */
public class ItemFormBinder extends AbstractFormBinder<Item>{

    private EditText mExpirationDate;
    private EditText mName;
    private MultiAutoCompleteTextView mTags;
    private ImageView mPicture;

    private String pictureUid;

    @Override
    protected ItemsBroker getClientBroker() {
        return new ItemsBroker(AbstractAdapter.API_ENDPOINT);
    }

    @Override
    public AModel makeObject(final Activity activity) {

        final String name = mName.getText().toString();
        final String expirationDate = mExpirationDate.getText().toString();

        final Item i = new Item();
        i.setName(name);
        i.setExpireDate(expirationDate, activity.getString(R.string.date_format));


        if(mTags.getText() != null){
            final String rawText = mTags.getText().toString();
            final String[] tags = rawText.split("[,]");
            for(String tag : tags)
                i.addTag(tag);
        }

        i.setAttachmentId(pictureUid);

        return i;
    }

    private void showDatePickerDialog(Activity activity, View v){
        final DatePickerFragment newFragment = new DatePickerFragment();
        newFragment.setListener(this);
        newFragment.show(activity.getFragmentManager(), "datePicker");

    }

    @Override
    public void bindObject(final Activity activity, Item obj) {
        mName.setText(obj.getName());
        mExpirationDate.setText(obj.getExpireDate(activity.getString(R.string.date_format)));
        mTags.setText(obj.getTagsToString(","));
        if(obj.getAttachmentId() != null){
            //FIXME: use cache service
            new GetAttachmentTask().execute(obj.getAttachmentId());
        }

    }

    @Override
    public void onCreate(final Activity activity){
        mExpirationDate = (EditText)activity.findViewById(R.id.expirationDate);
        mName = (EditText)activity.findViewById(R.id.name);


        final ImageView mBtnDatePicker = (ImageView)activity.findViewById(R.id.btnDatePicker);
        mBtnDatePicker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDatePickerDialog(activity, view);
            }
        });

        mTags = (MultiAutoCompleteTextView) activity.findViewById(R.id.tags);

        final TagsAdapter tagsAdapter = new TagsAdapter(activity.getLayoutInflater(),null, activity, null );
        tagsAdapter.fetch();
        mTags.setAdapter(tagsAdapter);
        mTags.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());

        mPicture = (ImageView)activity.findViewById(R.id.itemPicture);
        mPicture.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                FormActivity form = (FormActivity)activity;
                form.takePicture();
            }
        });


    }

    @Override
    public void returnDate(String formattedDate){
        mExpirationDate.setText(formattedDate);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == FormActivity.REQUEST_CODE_IMAGE_CAPTURE && resultCode == FormActivity.RESULT_OK) {
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data"); //FIXME
            mPicture.setImageBitmap(imageBitmap);


            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            byte[] bitmapdata = stream.toByteArray();

            Attachment att = new Attachment();
            att.setFileName("item_picture_" + System.currentTimeMillis() + ".jpg");
            att.setFileSize(bitmapdata.length);

            AttachmentUpload upload = new AttachmentUpload(att, bitmapdata);

            new SaveAttachmentTask().execute(upload);

        }
    }

    private class AttachmentUpload{
        protected Attachment attachment;
        protected byte[] data;

        public AttachmentUpload(Attachment attachment, byte[] data){
            this.attachment = attachment;
            this.data = data;
        }

    }


    private class GetAttachmentTask extends AsyncTask<String, Void, byte[]> {

        @Override
        protected byte[] doInBackground(String... params) {
            try {

                String _id;
                if(params != null && params.length > 0)
                    _id = params[0];
                else
                    _id = null;


                Log.d(TAG, "Retrieving picture with _id: " + _id);

                AttachmentsBroker broker = new AttachmentsBroker(AbstractAdapter.API_ENDPOINT)  ;
                byte[] b =  broker.getFile(_id);
                Log.d(TAG, "Byte array is not null: " + (b != null));
                return b;

            } catch (Exception e) {
                Log.e("SaveAttachmentTask", e.getMessage(), e);
            }

            return null;
        }

        @Override
        protected void onPostExecute(byte[] obj) {

            Log.d("SaveAttachmentTask", "OnPostExecute:" + obj);

            if(obj != null){
                Log.d(TAG, "Picture retrieved, setting to imageView: ");
                mPicture.setImageDrawable(null);
                mPicture.setImageBitmap(BitmapFactory.decodeByteArray(obj, 0, obj.length));
            }

        }

    }

    private class SaveAttachmentTask extends AsyncTask<AttachmentUpload, Void, Attachment> {

        @Override
        protected Attachment doInBackground(AttachmentUpload... params) {
            try {

                final AttachmentUpload upload;
                if(params != null && params.length > 0)
                    upload = params[0];
                else
                    upload = null;


                AttachmentsBroker broker = new AttachmentsBroker(AbstractAdapter.API_ENDPOINT)  ;
                return broker.putFile(upload.attachment, upload.data);

            } catch (Exception e) {
                Log.e("SaveAttachmentTask", e.getMessage(), e);
            }

            return null;
        }

        @Override
        protected void onPostExecute(Attachment obj) {

            Log.d("SaveAttachmentTask", "OnPostExecute:" + obj);


            if(obj.isSuccess()){
                pictureUid = obj.get_id();
            }

        }

    }


}


